<template>
    <!-- 渲染组件 - canvas艺术字 -->
    <canvas ref="canvas"></canvas>
</template>

<script>
export default {
    name: "RenderCanvasText",
    props: {
        element: {
            type: Object
        },
        Api: {
            type: Object
        },
        apiIndex: {
            type: Number,
            default: 0
        }
    },
    data() {
        return {
            context: null
        }
    },
    methods: {
        init(text) { // 渲染艺术字
            this.$refs.canvas.width = this.element.options.canvasWidth;
            this.$refs.canvas.height = this.element.options.canvasHeight;
            this.context = this.$refs.canvas.getContext("2d");
            // 1.清空画布
            this.context.clearRect(0, 0, this.$refs.canvas.offsetWidth, this.$refs.canvas.offsetHeight);
            // 2.字体样式
            let fontFamily = this.element.style.fontFamily == 'initial' ? 'sans-serif' : this.element.style.fontFamily;
            this.context.font = `${this.element.style.fontStyle} ${this.element.style.fontWeight} ${this.element.style.fontSize} ${fontFamily}`;
            // 3.字体颜色
            this.context.fillStyle = this.element.style.color;
            // 4.字体居中（根据 x,y选择的位置进行居中处理）
            this.context.textAlign = this.element.style.textAlign;
            // // 5.基线对齐
            this.context.textBaseline = this.element.style.textBaseline;
            // 6.缩放处理
            this.context.scale(this.element.options.scale.x, this.element.options.scale.y);
            // 7.填充文字
            let measureText = this.context.measureText(text);
            if (measureText.width > this.element.options.canvasWidth) {
                this.context.fillText(text, 0, Number(this.element.style.fontSize.slice(0, -2)), this.element.options.canvasWidth);
            } else this.context.fillText(text, 0, Number(this.element.style.fontSize.slice(0, -2)));
        }
    },
    mounted() {
        this.$nextTick(() => {
            if (this.element.options.contentField) { // 有绑定字段
                let contentField = this.element.options.contentField.split(':');
                let data = this.Api.options[Number(contentField[0])]?.data || null;
                if (data) {
                    let content = data?.[contentField[1]] || '';
                    this.init(content);
                }
            } else { // 无绑定字段，使用测试字段预览
                this.init(this.element.options.content);
            }
        })
    }
}
</script>
